<script setup lang="ts">
import { computed, unref } from 'vue'
import { ElIcon } from 'element-plus'
import { Icon } from '@iconify/vue'

const { getPrefixCls } = useDesignHooks()

const prefixCls = getPrefixCls('icon')

const props = defineProps({
  // icon name
  icon: {
    require: true,
    type: String,
    default: '',
  },
  // icon color
  color: {
    type: String,
    default: 'var(--el-input-icon-color)',
  },
  // icon size
  size: {
    type: [String, Number],
    default: 16,
  },
  hoverColor: {
    type: String,
    default: '',
  },
  svgClass: {
    type: String,
    default: '',
  },
})

const isLocal = computed(() => {
  return props.icon.startsWith('svg-icon:')
})

const symbolId = computed(() => {
  return unref(isLocal) ? `#icon-${props.icon.split('svg-icon:')[1]}` : props.icon
})

// 是否使用在线图标
const isUseOnline = computed(() => {
  return import.meta.env.VITE_USE_ONLINE_ICON === 'true'
})

const getIconifyStyle = computed(() => {
  const { color, size } = props
  return {
    fontSize: `${size}px`,
    color,
  }
})

const getSvgClass = computed(() => {
  const { svgClass } = props
  return `iconify ${svgClass}`
})
</script>

<template>
  <ElIcon :class="prefixCls" :size="size" :color="color">
    <svg v-if="isLocal" aria-hidden="true" :class="getSvgClass">
      <use :xlink:href="symbolId" />
    </svg>

    <template v-else>
      <Icon v-if="isUseOnline" :class="getSvgClass" :icon="icon" :style="getIconifyStyle" />
      <div v-else :class="`${icon} iconify`" :style="getIconifyStyle"></div>
    </template>
  </ElIcon>
</template>

<style lang="scss" scoped>
$prefix-cls: #{$namespace}-icon;

.#{$prefix-cls},
.iconify {
  fill: v-bind(color);

  :deep(svg) {
    &:hover {
      // stylelint-disable-next-line
      color: v-bind(hoverColor) !important;
      fill: v-bind(hoverColor) !important;
    }
  }
}

.iconify {
  &:hover {
    // stylelint-disable-next-line
    color: v-bind(hoverColor) !important;
  }
}
</style>
